package org.theqcp.wow.api.wowarmory.parsers;

import java.util.ArrayList;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.xpath.XPath;
import org.theqcp.wow.api.wowarmory.parsers.talents.AbstractTalentParser;
import org.theqcp.wow.api.wowarmory.parsers.talents.TalentParserFactory;
import org.theqcp.wow.model.api.ProgressListener;
import org.theqcp.wow.model.api.ProgressListenerAdapter;
import org.theqcp.wow.model.mechanics.ClassType;
import org.theqcp.wow.model.player.Talent;

public class TalentTabParser extends AbstractParser{

	public List<Talent> parse(Document inputDocument, ProgressListener listener) {
		
		//talent list
		ArrayList<Talent> talentList = new ArrayList<Talent>();
		
		try {

			//get element(s) with xpath
			XPath xpath = XPath.newInstance("/page/characterInfo");
			
			//list
			@SuppressWarnings("unchecked")
			List<Element> elementList = xpath.selectNodes(inputDocument);
			
			if(elementList != null && elementList.size() > 0) {
			
				if(listener != null) {
					listener.updateProgress(0, "Parsing raw talent data.");
				}
				
				//get first (character) node
				Element characterInfoElement = (Element)elementList.get(0);
				
				//get name, realm, class, race
				String clazz = characterInfoElement.getChild("character").getAttributeValue("class");
				ClassType classType = ClassType.getClassFromName(clazz);

				//get element
				Element talentElement = characterInfoElement.getChild("talentTab").getChild("talentTree");
				String talentString = talentElement.getAttributeValue("value");
				
				//create int array
				int[] talents = new int[talentString.length()];
				//populate talent array
				for(int i = 0; i < talentString.length(); i++) {
					talents[i] = this.convertSafeInt("" + talentString.charAt(i));
				}
				
				if(listener != null) {
					listener.updateProgress(10, "Enumerating talents.");
				}

				
				//talentsubsection 90%
				ProgressListenerAdapter pla = new ProgressListenerAdapter(listener, 10.0, 100.0);
				
				//get talent parser
				AbstractTalentParser parser = TalentParserFactory.createTalentParser(classType);
				talentList = parser.parse(talents, pla);
				
			}
			
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		
		
		return talentList;
	}
}
